<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>兴趣社群聊天室测试</title>
    <style>
        body {
            font-family: "Helvetica Neue", sans-serif;
            background-color: #f5f5f5;
            padding: 30px;
        }

        h2 {
            text-align: center;
            color: #333;
        }

        .user-info {
            text-align: center;
            margin-bottom: 20px;
        }

        .user-info input {
            padding: 6px;
            font-size: 14px;
            width: 180px;
            margin: 0 10px;
        }

        #chat {
            background-color: #fff;
            border: 1px solid #ddd;
            height: 300px;
            overflow-y: auto;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 5px;
        }

        #chat p {
            margin: 8px 0;
            padding: 4px 8px;
            border-radius: 4px;
        }

        #chat p.gray {
            color: #888;
            background-color: #f0f0f0;
        }

        #chat p.new {
            color: #333;
            background-color: #d9f1ff;
        }

        #msg {
            width: calc(100% - 100px);
            padding: 10px;
            font-size: 16px;
            border-radius: 4px;
            border: 1px solid #ccc;
        }

        button {
            padding: 10px 18px;
            font-size: 16px;
            margin-left: 10px;
            background-color: #007bff;
            color: #fff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        button:hover {
            background-color: #0056b3;
        }
    </style>
</head>
<body>

<h2>社区聊天室 (ID=1)</h2>

<div class="user-info">
    <label>用户ID：<input id="uid" value="1"></label>
    <label>昵称：<input id="nickname" value="用户A"></label>
    <label>社群ID：<input id="communityId" value="1"></label>
    <!-- ✅ 页面隐藏一个 input 存用户 token -->
    <input type="hidden" id="token" value="911f128c-96e6-429b-bfda-3ee7b1c0b3c5" />

</div>
<div id="notificationLog" style="background-color: #fff8e1; border: 1px solid #ccc; padding: 10px; margin-bottom: 20px; border-radius: 5px;">
    <strong>📢 WebSocket 通知日志：</strong>
    <div id="logContent" style="max-height: 150px; overflow-y: auto; font-size: 14px;"></div>
</div>


<div id="chat"></div>

<div style="text-align: center;">
    <input type="text" id="msg" placeholder="输入消息...">
    <button onclick="sendMessage()">发送</button>
    <input type="file" id="imageInput" accept="image/*" onchange="previewImage()">
    <button onclick="uploadImage()">上传图片</button>
    <button onclick="connect()">连接聊天室</button>
    <button onclick="loadMore()">加载更多历史消息</button>
    <button onclick="applyToJoin()">申请加入群聊</button>
    <button onclick="reviewApplications()">审批加群申请（群主）</button>
    <br>
    <p id="uploadHint" style="color: #888; display: none;">如预览正确，请点击上传发送</p>
    <img id="imagePreview" src="" alt="图片预览" style="max-width: 200px; margin-top: 10px; display: none; border: 1px solid #ccc;">
</div>
<!-- 点击放大预览图片 Modal -->
<div id="imgModal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background-color:rgba(0,0,0,0.7); justify-content:center; align-items:center; z-index:9999;"
     onclick="closeModal()">
    <img id="modalImage" src="" style="max-width:90%; max-height:90%; border:5px solid #fff; border-radius:8px;">
</div>


<script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/stompjs@2.3.3/lib/stomp.min.js"></script>
<script>
    let stompClient = null;
    //const communityId = 1;
    let currentPage = 1;
    const pageSize = 20;



    function connect() {
        const userId = document.getElementById("uid").value;
        const communityId = document.getElementById("communityId").value;
        const token = 'Bearer fa08adc6-d02e-49c0-9f37-146ef6a1eca3'; // 群主 token，可从 localStorage 等处动态获取
        const socket = new WebSocket(`ws://localhost:8080/ws-chat/websocket?userId=${userId}&communityId=${communityId}`);
        //const socket = new SockJS(`/ws-chat?userId=${userId}&communityId=${communityId}`);
        stompClient = Stomp.over(socket);

        // 设置 STOMP 调试日志可见
        stompClient.debug = function (str) {
            console.log('[STOMP]', str);
        };

        stompClient.connect({ Authorization: token }, function (frame) {
            console.log("✅ STOMP 连接成功:", frame);

            // ✅ 订阅通知消息（必须放在 connect 成功回调中）
            console.log("📌 正在订阅通知...");
            stompClient.subscribe(`/topic/notifications-${userId}`, function (msg) {
                console.log("✅ 收到通知:", msg.body);
                const notice = JSON.parse(msg.body);
                appendToLog(`[${notice.type}] ${notice.content}`);
            });

            // stompClient.subscribe("/user/topic/notifications", function (msg) {
            //     console.log("✅ 收到通知:", msg.body);
            //     const notice = JSON.parse(msg.body);
            //     appendToLog(`[${notice.type}] ${notice.content}`);
            // }, {}, function (ackFrame) {
            //     console.log("📌 已订阅通知通道成功:", ackFrame);
            // });

            // ✅ 订阅社群聊天频道
            stompClient.subscribe(`/topic/chat/${communityId}`, function (msg) {
                console.log("💬 收到群聊消息");
                const chat = JSON.parse(msg.body);
                const chatBox = document.getElementById("chat");

                const msgElement = document.createElement("p");
                msgElement.className = "new";
                const timeHtml = `<small style="color: #aaa;">(${formatTime(chat.createdAt)})</small>`;

                if (chat.messageType === "image") {
                    msgElement.innerHTML = `${chat.senderNickname} ${timeHtml}:<br><img src="${chat.content}" style="max-width: 120px; cursor: pointer;" onclick="showModal('${chat.content}')">`;
                } else {
                    msgElement.innerHTML = `${chat.senderNickname} ${timeHtml}: ${chat.content}`;
                }

                chatBox.appendChild(msgElement);
                scrollToBottom();
            });

            // ✅ 加载第一页历史消息
            loadMore();

            // ✅ 启用滚动加载
            const chatBox = document.getElementById("chat");
            chatBox.addEventListener("scroll", function () {
                if (this.scrollTop === 0) {
                    loadMore();
                }
            });
        }, function (error) {
            console.error("❌ STOMP 连接失败:", error);
        });
    }

    function applyToJoin() {
        const userId = document.getElementById("uid").value;
        const communityId = document.getElementById("communityId").value; // ✅ 改为从输入框获取
        const reason = prompt("请输入申请理由：", "想加入聊天");
        if (!reason) return;

        fetch(`/api/community/applications/apply?communityId=${communityId}&reason=${encodeURIComponent(reason)}`, {
            method: "POST",
            headers: {
                'Authorization': 'Bearer fa08adc6-d02e-49c0-9f37-146ef6a1eca3'
            }
        })
            .then(resp => resp.json())
            .then(res => {
                if (res.code === 1) {
                    alert("申请已提交，等待群主审批");
                } else {
                    alert("申请失败：" + res.msg);
                }
            });
    }

    function reviewApplications() {
        const userId = document.getElementById("uid").value;
        const communityId = document.getElementById("communityId").value;

        fetch(`/api/community/applications/pending?communityId=${communityId}`, {
            headers: {
                'Authorization': 'Bearer fa08adc6-d02e-49c0-9f37-146ef6a1eca3'
            }
        })
            .then(res => res.json())
            .then(data => {
                if (data.code !== 1 || !data.data) return alert("获取失败：" + data.msg);
                const applications = data.data;

                if (applications.length === 0) return alert("暂无待处理申请");

                const approve = confirm(`申请人：用户${applications[0].userId}\n理由：${applications[0].reason}\n点击确定同意，取消则拒绝`);

                fetch(`/api/community/applications/review?applicationId=${applications[0].id}&status=${approve ? 'APPROVED' : 'REJECTED'}`, {
                    method: "POST",
                    headers: {
                        'Authorization': 'Bearer fa08adc6-d02e-49c0-9f37-146ef6a1eca3'
                    }
                })
                    .then(r => r.json())
                    .then(res => {
                        if (res.code === 1) {
                            alert("处理成功");
                        } else {
                            alert("处理失败：" + res.msg);
                        }
                    });
            });
    }


    function loadMore() {
        const communityId = document.getElementById("communityId").value;
        fetch(`/api/chat/history?communityId=${communityId}&page=${currentPage}&size=${pageSize}`, {
            headers: {
                'Authorization': 'Bearer fa08adc6-d02e-49c0-9f37-146ef6a1eca3'
            }
        })
            .then(response => response.json())
            .then(res => {
                const list = res.data;
                if (!Array.isArray(list) || list.length === 0) return;

                const chatBox = document.getElementById("chat");

                list.forEach(msg => {
                    const msgElement = document.createElement("p");
                    msgElement.className = "gray";
                    const timeHtml = `<small style="color:#aaa">(${formatTime(msg.createdAt)})</small>`;

                    if (msg.messageType === "image") {
                        msgElement.innerHTML = `[历史] ${msg.senderNickname} ${timeHtml}:<br><img src="${msg.content}" style="max-width: 120px; cursor: pointer;" onclick="showModal('${msg.content}')">`;
                    } else {
                        msgElement.innerHTML = `[历史] ${msg.senderNickname} ${timeHtml}: ${msg.content}`;
                    }

                    chatBox.prepend(msgElement);
                });

                currentPage++;
            });
    }
    function appendToLog(text) {
        const logArea = document.getElementById("logContent");
        const p = document.createElement("p");
        const timestamp = new Date().toLocaleTimeString();
        p.textContent = `[${timestamp}] ${text}`;
        logArea.appendChild(p);
        logArea.scrollTop = logArea.scrollHeight;
    }

    function formatTime(timestamp) {
        if (!timestamp) return '';
        const date = new Date(timestamp);

        // 修正时区差（减去 8 小时）——适用于后端返回的是 UTC
        date.setHours(date.getHours() - 8);

        return date.toLocaleString(); // 现在会是北京时间
    }


    function sendMessage() {
        const communityId = document.getElementById("communityId").value;
        const content = document.getElementById("msg").value;
        const userId = document.getElementById("uid").value;
        const nickname = document.getElementById("nickname").value;

        const message = {
            senderId: userId,
            senderNickname: nickname,
            content: content
        };
        stompClient.send(`/app/chat/${communityId}`, {}, JSON.stringify(message));
        document.getElementById("msg").value = '';
    }
    function showModal(url) {
        const modal = document.getElementById("imgModal");
        const modalImage = document.getElementById("modalImage");
        modalImage.src = url;
        modal.style.display = "flex";
    }

    function closeModal() {
        document.getElementById("imgModal").style.display = "none";
    }

    function uploadImage() {
        const communityId = document.getElementById("communityId").value;
        const fileInput = document.getElementById("imageInput");
        const file = fileInput.files[0];
        if (!file) {
            alert("请选择图片");
            return;
        }

        compressImage(file, 0.7, function (compressedBlob) {
            const formData = new FormData();
            formData.append("file", compressedBlob, file.name); // 保留原始文件名

            fetch("/api/common/upload", {
                method: "POST",
                body: formData,
                headers: {
                    'Authorization': 'Bearer fa08adc6-d02e-49c0-9f37-146ef6a1eca3'
                }
            })
                .then(response => response.json())
                .then(res => {
                    if (res.code === 1) {
                        const imageUrl = res.data;
                        const userId = document.getElementById("uid").value;
                        const nickname = document.getElementById("nickname").value;

                        const message = {
                            senderId: userId,
                            senderNickname: nickname,
                            content: imageUrl,
                            messageType: "image"
                        };

                        stompClient.send(`/app/chat/${communityId}`, {}, JSON.stringify(message));
                    } else {
                        alert("上传失败：" + res.msg);
                    }
                })
                .catch(err => {
                    console.error("上传失败", err);
                    alert("上传失败");
                });
        });
    }

    function compressImage(file, quality = 0.7, callback) {
        const reader = new FileReader();
        reader.readAsDataURL(file);

        reader.onload = function (e) {
            const img = new Image();
            img.src = e.target.result;

            img.onload = function () {
                const canvas = document.createElement("canvas");
                const ctx = canvas.getContext("2d");

                const MAX_WIDTH = 800;
                const scale = Math.min(MAX_WIDTH / img.width, 1);
                canvas.width = img.width * scale;
                canvas.height = img.height * scale;

                ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

                canvas.toBlob(function (blob) {
                    callback(blob);
                }, "image/jpeg", quality); // 压缩为 jpeg 格式
            };
        };
    }

    function previewImage() {
        const fileInput = document.getElementById("imageInput");
        const preview = document.getElementById("imagePreview");
        const hint = document.getElementById("uploadHint");
        const file = fileInput.files[0];

        if (file && file.type.startsWith("image/")) {
            const reader = new FileReader();
            reader.onload = function (e) {
                preview.src = e.target.result;
                preview.style.display = "block";
                hint.style.display = "block";
            };
            reader.readAsDataURL(file);
        } else {
            preview.src = "";
            preview.style.display = "none";
            hint.style.display = "none";
        }
    }

    function scrollToBottom() {
        const chatBox = document.getElementById("chat");
        chatBox.scrollTop = chatBox.scrollHeight;
    }



    //connect();
</script>

</body>
</html>
